﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Data.Sql;

namespace Views
{
    /// <summary>
    /// Interaction logic for ucCompareDatabaseView.xaml
    /// </summary>
    public partial class ucCompareDatabaseView : UserControl
    {
        private bool ReLoad1 = true;
        private bool ReLoad2 = true;
        private bool firstload = true;
        Models.DataModel Conn1 = new Models.DataModel();
        Models.DataModel Conn2 = new Models.DataModel();    

        public ucCompareDatabaseView()
        {
            InitializeComponent();
            Models.LogEvent.Log.Columns.Add("Log");
        }

        private void checkConnection1(string database)
        {
            Conn1 = new Models.DataModel(cbServer1.Text, (bool)rbtSqlAuthentication1.IsChecked, database, txtUser1.Text, txtPass1.Text);
            bd1.Visibility = Conn1.CheckConnection() ? Visibility.Hidden : Visibility.Visible;
        }

        private void checkConnection2(string database)
        {
            Conn2 = new Models.DataModel(cbServer2.Text, (bool)rbtSqlAuthentication2.IsChecked, database, txtUser2.Text, txtPass2.Text);
            bd2.Visibility = Conn2.CheckConnection() ? Visibility.Hidden : Visibility.Visible;
        }

        private void rbtWindowAuthentication1_Click(object sender, RoutedEventArgs e)
        {
            txtUser1.IsEnabled = txtPass1.IsEnabled = !(bool)rbtWindowAuthentication1.IsChecked;
            txtUser2.IsEnabled = txtPass2.IsEnabled = !(bool)rbtWindowAuthentication2.IsChecked;
            if ((sender as RadioButton).Name == "rbtWindowAuthentication1" || (sender as RadioButton).Name == "rbtSqlAuthentication1")
            {
                ReLoad1 = true;
                checkConnection1(cbDatabase1.Text);
            }
            else //if ((sender as RadioButton).Name == "rbtWindowAuthentication2" || (sender as RadioButton).Name == "rbtSqlAuthentication2")
            {
                ReLoad2 = false;
                checkConnection2(cbDatabase2.Text);
            }
        }

        private void cbDatabase1_GotFocus(object sender, RoutedEventArgs e)
        {
            if (ReLoad1)
                cbDatabase1.ItemsSource = ModelViews.CompareDatabaseModelView.GetAllDatabase(cbServer1.Text, (bool)rbtSqlAuthentication1.IsChecked, "", txtUser1.Text, txtPass1.Text).DefaultView;
            ReLoad1 = false;
        }

        private void cbDatabase2_GotFocus(object sender, RoutedEventArgs e)
        {
            if (ReLoad2)
                cbDatabase2.ItemsSource = ModelViews.CompareDatabaseModelView.GetAllDatabase(cbServer2.Text, (bool)rbtSqlAuthentication2.IsChecked, "", txtUser2.Text, txtPass2.Text).DefaultView;
            ReLoad2 = false;

        }

        private void cbServer1_GotFocus(object sender, RoutedEventArgs e)
        {
            ReLoad1 = true;
        }

        private void cbServer2_GotFocus(object sender, RoutedEventArgs e)
        {
            ReLoad2 = true;
        }

        private void cbDatabase1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                checkConnection1((sender as ComboBox).SelectedValue.ToString());
            }
            catch { return; }
        }

        private void cbDatabase2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                checkConnection2((sender as ComboBox).SelectedValue.ToString());
            }
            catch { return; }
        }

        private void txtPass1_TextChanged(object sender, TextChangedEventArgs e)
        {
            checkConnection1(cbDatabase1.Text);
        }

        private void txtUser2_TextChanged(object sender, TextChangedEventArgs e)
        {
            checkConnection2(cbDatabase2.Text);
        }

        private void btnSync_Click(object sender, RoutedEventArgs e)
        {

            Models.LogEvent.Log.Rows.Clear();         
            DataTable tb1 = new DataTable();//Table_Define
            DataTable tb2 = new DataTable();//Table_Index
            DataTable tb3 = new DataTable();//Table_identity
            DataTable tb4 = new DataTable();//Store
            DataTable tb5 = new DataTable();//Views

            string BeginDate = string.Empty;
            string EndDate = string.Empty;

            if (string.IsNullOrEmpty(cbDatabase1.Text) || string.IsNullOrEmpty(cbDatabase2.Text))
            {
                MessageBox.Show("Chưa Chọn DataBase", "Message",MessageBoxButton.OK,MessageBoxImage.Error);
                return;
            }

            if ((bool)cbStore.IsChecked)
            {
                if (xdtBegin.Value == null)
                {
                    MessageBox.Show("Chưa nhập ngày bắt đầu!", "Lỗi");
                    xdtBegin.Focus();
                    return;
                }
                else if (xdtEnd.Value == null)
                {
                    MessageBox.Show("Chưa nhập ngày kết thúc!", "Lỗi");
                    xdtEnd.Focus();
                    return;
                }
                else if ((DateTime)xdtBegin.Value < (DateTime)xdtBegin.Value)
                {
                    MessageBox.Show("ngày bắt đầu không được nhỏ hơn ngày kết thúc!", "Lỗi");
                    xdtBegin.Focus();
                    return;
                }
                BeginDate = string.Format("{0:yyyyMMdd}", xdtBegin.Value.ToString());
                EndDate = string.Format("{0:yyyyMMdd}", xdtEnd.Value.ToString());
                //tb4 = Models.CompareStoreModel.ProcedureList(Conn1, BeginDate, EndDate);
            }

            //frmWaitingView Waiting = new frmWaitingView("Compare Running...");
            //Waiting.SetValue(70);
            //Waiting.Show(); 
            Conn1 = new Models.DataModel(cbServer1.Text, (bool)rbtSqlAuthentication1.IsChecked, cbDatabase1.Text, txtUser1.Text, txtPass1.Text);
            Conn2 = new Models.DataModel(cbServer2.Text, (bool)rbtSqlAuthentication2.IsChecked, cbDatabase2.Text, txtUser2.Text, txtPass2.Text);   
            frmProcessesUpdate frm = new frmProcessesUpdate();
            string connetion = Conn1.conn.ConnectionString;
            if ((bool)cbTable.IsChecked)
            {
                frm.message("Please waiting for create update TABLE...!");
                frm.Show();
                tb1 = ModelViews.CompareDatabaseModelView.CompareTable(Conn1, Conn2, 0);
                //Waiting.SetValue(80);
                tb2 = ModelViews.CompareDatabaseModelView.CompareTable(Conn1, Conn2, 1);
                //Waiting.SetValue(90);
                tb3 = ModelViews.CompareDatabaseModelView.CompareTable(Conn1, Conn2, 2);                
            }

            //Waiting.SetValue(100);
            DataTable tbTable = new DataTable();
            DataTable tbError1 = new DataTable();
            DataTable tbError2 = new DataTable();
            DataTable tbError3 = new DataTable();
            DataTable tbError = new DataTable();
            if ((bool)cbTable.IsChecked)
            {
                Conn1.conn.ConnectionString = connetion;
                tbTable = ModelViews.UpdateDatabaseModelView.CreateScript(Conn1, tb1, tb2, tb3);
                frm.Close();
                tbError = Models.DataModel.MixTable(tbError, ModelViews.UpdateDatabaseModelView.BeginUpdateTable(Conn2, tbTable));
            }
            if ((bool)cbViews.IsChecked)
            {
                tbError = Models.DataModel.MixTable(tbError, ModelViews.UpdateDatabaseModelView.BeginUpdateViews(Conn1, Conn2));
            }
            if ((bool)cbStore.IsChecked)
            {
                tbError = Models.DataModel.MixTable(tbError, ModelViews.UpdateDatabaseModelView.BeginUpdateStored(Conn1, Conn2, BeginDate, EndDate));
            }
            if ((bool)cbdmFile.IsChecked)
            {
                //tbError = Models.DataModel.MixTable(tbError, ModelViews.UpdateDatabaseModelView.BeginUpdateDmFile(Conn1, Conn2));
                tbError = Models.DataModel.MixTable(tbError, ModelViews.UpdateDatabaseModelView.BeginUpdateDmFile_NoOpenRowSet(Conn1, Conn2));
            }
            if ((bool)cbdmBc.IsChecked)
            {
                //tbError = Models.DataModel.MixTable(tbError, ModelViews.UpdateDatabaseModelView.BeginUpdateDmBc(Conn1, Conn2));
                tbError = Models.DataModel.MixTable(tbError, ModelViews.UpdateDatabaseModelView.BeginUpdateDmBc_NoOpenRowSet(Conn1, Conn2));
            }

            if (tbError.Rows.Count > 0)
                (new frmError(tbError)).ShowDialog();
            (new frmUpdateFinish("Upadate Finish!!")).ShowDialog();
        }

        private void btnAnalysis_Click(object sender, RoutedEventArgs e)
        {
            Models.LogEvent.Log.Rows.Clear(); 
            DataTable tb1 = new DataTable();
            DataTable tb2 = new DataTable();
            DataTable tb3 = new DataTable();

            if (string.IsNullOrEmpty(cbDatabase1.Text) || string.IsNullOrEmpty(cbDatabase2.Text))
            {
                MessageBox.Show("Chưa Chọn DataBase", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }         

            frmWaitingView Waiting = new frmWaitingView("Compare Running...");
            Waiting.SetValue(70);
            Waiting.Show();
            
            if ((bool)cbTable.IsChecked)
            {
                tb1 = ModelViews.CompareDatabaseModelView.CompareTable(Conn1, Conn2, 0);
                Waiting.SetValue(80);
                tb2 = ModelViews.CompareDatabaseModelView.CompareTable(Conn1, Conn2, 1);
                Waiting.SetValue(90);
                tb3 = ModelViews.CompareDatabaseModelView.CompareTable(Conn1, Conn2, 2);
            }
            
            Waiting.SetValue(100);
            (new frmUpdateDatabaseView(Conn1, Conn2, tb1, tb2, tb3)).Show();
        }

        private void cbServer1_DropDownOpened(object sender, EventArgs e)
        {
            if (!firstload)
                return;
            string waiting = " (Loading...)";
            ((Window)this.Parent).Title += waiting;
            DataTable tb = new DataTable();
            tb = SqlDataSourceEnumerator.Instance.GetDataSources();
            DataTable _tb = new DataTable();
            _tb.Columns.Add("InstanceName");
            foreach (DataRow row in tb.Rows)
            {
                _tb.Rows.Add(row["ServerName"].ToString() + "\\" + row["InstanceName"].ToString());
            }
            cbServer1.ItemsSource = _tb.DefaultView;
            cbServer2.ItemsSource = _tb.DefaultView;
            ((Window)this.Parent).Title = ((Window)this.Parent).Title.Substring(0, ((Window)this.Parent).Title.Length - waiting.Length);
            firstload = false;
        }

        private void ucCompareData_Loaded(object sender, RoutedEventArgs e)
        {
            xdtBegin.Focus();
        }
    }
}
